package com.dfd.producer.service.impl;

import com.dfd.common.exception.CustomException;
import com.dfd.common.utils.IdWorker;
import com.dfd.producer.mapper.MqRecordMapper;
import com.dfd.producer.service.MqProducerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: Fengdong.Duan
 * @Date: 2023/2/9 13:22
 */
@Service
@Slf4j
public class MqProducerServiceImpl implements MqProducerService {

    @Autowired
    IdWorker idWorker;
    @Autowired
    MqRecordMapper mqRecordMapper;
    @Autowired
    DefaultMQProducer defaultMQProducer;


    /**
     * 发送消息到MQ
     *
     * @param msg
     * @return
     */
    @Override
    public SendResult send(String msg) {
        SendResult sendResult = null;
        if (StringUtils.isEmpty(msg)) {
            throw new CustomException("消息为空！");
        }
        //执行业务
        //.......
        //执行结束
        Long businessId = idWorker.nextId();
        //先写硬编码
        String topic = "spring-boot-topic";
        String tag = "tag1";
        try {
            // 封装消息对象
            Message message = new Message();
            message.setBody(msg.getBytes());
            message.setKeys(String.valueOf(businessId));
            message.setTopic(topic);
            message.setTags(tag);
            sendResult = defaultMQProducer.send(message);
            if (SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
                log.info("消息发送成功，发送MQ消息内容：{}，业务ID：{}，消息ID：{}", msg, businessId, sendResult.getMsgId());
            }
        } catch (Exception e) {
            log.info("消息发送失败，发送MQ消息内容：{}，业务ID：{}，失败原因：{}", msg, businessId, e.toString());
        }
//        //失败也要存，用作补偿
//        MqRecord record = MqRecord.builder()
//                .msgId(StringUtils.isNotBlank(sendResult.getMsgId()) ? sendResult.getMsgId() : null)
//                .businessId(businessId)
//                .content(msg)
//                .topic(topic)
//                .tag(tag)
//                .createTime(new Date())
//                .build();
//        mqRecordMapper.insert(record);
        return sendResult;
    }
}
